@<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意,只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        :show-icon="true"
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cart_opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品级联区域 -->
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签 区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            size="mini"
            type="primary"
            @click="addDialog"
            >添加参数</el-button
          >

          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 可展开区域 -->
            <el-table-column type="expand">
              <!-- 循环渲染 tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                >
                  {{ item }}
                </el-tag>

                <!-- 新增按钮和输入框 区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  class="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  class="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            size="mini"
            type="primary"
            @click="addDialog"
            >添加属性</el-button
          >

          <!-- 静态属性区域 -->
          <el-table :data="onlyTableData">
            <!-- 添加修改静态属性的面板 -->
            <el-table-column type="expand">
              <!-- 循环渲染 tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                >
                  {{ item }}
                </el-tag>

                <!-- 新增按钮和输入框 区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  class="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  class="el-icon-delete"
                  @click="deleteParam(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态属性或静态参数的对话框 -->
    <el-dialog
      @close="closeDialog"
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改动态参数或属性的对话框 -->

    <el-dialog
      @close="closeEditDialog"
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="editFormRules"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除参数或属性的对话框 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      cateList: [],

      // 级联框配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择的列表对象
      selectKeys: [],

      // tab页签绑定name,被激活的标签名
      activeName: "many",

      // 保存动态参数
      manyTableData: [],

      // 保存静态属性
      onlyTableData: [],

      // 控制添加对话框是否展开
      addDialogVisible: false,

      // 添加数据对象
      addForm: {
        attr_name: "",
      },
      // 修改数据对象
      editForm: {},

      // 添加参数表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      // 修改参数的表单验证规则
      editFormRules: {
        attr_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      // 修改对话框是否显示
      editDialogVisible: false,
      // 修改对象的id
      editAttrid: "",
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);

      if (res.meta.status != 200)
        return this.$message.error("商品分离数据获取失败");
      this.cateList = res.data;
    },
    // 级联框选择后触发的函数
    handleChange() {
      this.getParamsData();
    },
    //获取参数的列表数据
    async getParamsData() {
      // 控制级联选择器选中范围
      if (this.selectKeys.length !== 3) {
        this.selectKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];

        return;
      }

      // 根据分类id和当前tab页面请求相应数据
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("商品信息获取失败");
      }
      // 删除数组空白的函数
      function removeSpace(arr) {
        arr.forEach((item, index) => {
          if (item.trim().length == 0) {
            arr.splice(index, 1);
          }
        });
        return arr;
      }

      res.data.forEach((item) => {
        item.attr_vals = removeSpace(item.attr_vals.split(","));
        // 控制文本框的显示或隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = "";
      });
      console.log(res.data);
      // 判断数据属于哪个 表格
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },

    // tab标签被点击的事件处理函数
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    // 展示添加对话框
    addDialog() {
      this.addDialogVisible = true;
    },
    // 对话框关闭事件,刷新form
    closeDialog() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加参数
    addParams() {
      // 表单预验证
      this.$refs.addFormRef.validate(async (valied) => {
        if (!valied) return;

        // 发送添加数据请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status != 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        this.getParamsData();
        this.addDialogVisible = false;
      });
    },
    // 点击编辑触发的处理函数
    async editParams(attr_id) {
      this.editAttrid = attr_id;
      // 发送数据获取对象
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("获取数据失败");
      }
      this.editForm = res.data;

      // 展示对话框
      this.editDialogVisible = true;
    },
    // 修改参数框关闭事件
    closeEditDialog() {},
    // 确认修改参数
    confirmEditParams() {
      // 表单预验证
      this.$refs.editFormRef.validate(async (valied) => {
        if (!valied) return;

        // 发送修改请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editAttrid}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status != 200) {
          return this.$message.error("修改失败!");
        }
        this.$message.success("修改成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    // 删除参数的操作
    async deleteParam(attrId) {
      const result = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result != "confirm") {
        return this.$message.info("取消删除");
      }
      // 删除业务逻辑
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      this.getParamsData();
    },
    // 失去焦点和按enter键的事件处理函数
    handleInputConfirm(item) {
      // 判断是否输入有效内容
      if (item.inputValue.trim().length == 0) {
        item.inputValue = "";
        item.inputVisible = false;
        return;
      }
      item.attr_vals.push(item.inputValue);

      // 保存参数操作
      this.saveAttr(item);
    },
    // 保存参数的函数
    async saveAttr(item, err = "添加失败", succes = "添加成功") {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${item.attr_id}`,
        {
          attr_name: item.attr_name,
          attr_sel: item.attr_sel,
          // 服务端接收的为字符串
          attr_vals: item.attr_vals.join(","),
        }
      );
      console.log(res);
      if (res.meta.status != 200) {
        return this.$message.error(err);
      }

      this.$message.success(succes);
      item.inputValue = "";
      item.inputVisible = false;
    },

    // 点击新增按钮的事件处理函数
    showInput(item) {
      item.inputVisible = true;
      // 页面被重新渲染才会调用的方法
      this.$nextTick((_) => {
        // 获取原生inputDOM对象添加focus方法
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // tag标签关闭事件
    deleteTag(index, item) {
      // 删除tag参数
      item.attr_vals.splice(index, 1);

      // 刷新保存参数
      this.saveAttr(item, "删除失败", "删除成功");
    },
  },
  computed: {
    // 控制按钮是否能被点击
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true;
      }
      return false;
    },

    // 选中的分类id值
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2];
      }
      return null;
    },
    // 动态更换名称
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="less" scope>
.cart_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 15px;
  width: 250px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag input {
  width: 150px;
}
</style>